<template>
  <view>
    <uni-popup ref="popup" type="center">
      <view class="title">获取位置失败 请检查当前手机GPS是否打开</view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { showLoading, errorToast } from '@/utils/prompt';
  import { onShow } from '@dcloudio/uni-app';
  import { defaultFail, getLocation } from '@/utils/wechat.jssdk';
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  window._AMapSecurityConfig = {
    securityJsCode: "c53255f5ea37ff63f333417d2ebe4e95",
  }
  const emits = defineEmits(['position']);
  const longitude = ref(0); //纬度113.62493
  const latitude = ref(0); //经度34.74725
  const popup = ref(null)
  onShow(() => {
    const time = Date.parse(new Date())
    const data = time - uni.getStorageSync('dataTime')
    const positions = uni.getStorageSync('position')
    if (!positions.longitude || data > 600000) {
      locationList();
    } else {
      emits('position', positions.latitude, positions.longitude);
    }
  })
  /**
   * 获取当前位置信息
   */
  function locationList() {
    showLoading('获取地理位置');
    function success(res : any) {
      uni.hideLoading();
      latitude.value = Number.parseFloat(res.latitude);
      longitude.value = Number.parseFloat(res.longitude);
      const position = {
        latitude: latitude.value,
        longitude: longitude.value
      }
      uni.setStorageSync('position', position);
      emits('position', latitude.value, longitude.value);
      uni.setStorageSync('dataTime', Date.parse(new Date()));
    }
    function fail() {
      // TODO
      setTimeout(() => {
        uni.getLocation({
          type: 'gcj02',
          altitude: true,
          success(res : any) {
            uni.hideLoading();
            latitude.value = Number.parseFloat(res.latitude);
            longitude.value = Number.parseFloat(res.longitude);
            const position = {
              latitude: latitude.value,
              longitude: longitude.value
            }
            uni.setStorageSync('position', position);
            emits('position', latitude.value, longitude.value);
            uni.setStorageSync('dataTime', Date.parse(new Date()));
          },
          fail() {
            popup.value.open()
            return
          }
        });
      }, 500);
    }
    getLocation(success, defaultFail('getLocation', fail));
  }
  defineExpose({
    locationList
  });
</script>

<style>
  .title {
    width: 80%;
    background-color: white;
    padding: 20rpx;
    box-sizing: border-box;
    border-radius: 5px;
    margin: 0px auto;
  }
</style>